#include <Arduino.h>
#include "thermistor.h"
#include "settings.h"


double Thermistor::CToK(double temp_in_C) {
  return temp_in_C + 273.15;
}


double Thermistor::KtoC(double temp_in_K) {
  return temp_in_K - 273.15;
}


double Thermistor::KtoF(double temp_in_K) {
  return (temp_in_K - 273.15) * 1.8 + 32.0;
}


double Thermistor::calc_rthermo(double v_thermistor) {
  double term1 = v_thermistor * this->r_divider;  // volt * ohm
  double term2 = this->v_ref - v_thermistor;  // volt - volt
  double result = term1 / term2;
  /*
  double result = (v_thermistor * this->r_divider) / (this->v_ref - v_thermistor);
  */
  return result;
}


// Calculates Temperature from Thermistor Voltage
// Returns Temperature in Kelvin
double Thermistor::calc_temp(double v_thermistor, const bool use_fahrenheit) {
  double r_thermistor = this->calc_rthermo(v_thermistor);
  double result;
  
  // long version
  result = r_thermistor / (double)this->r_beta;
  result = log(result);
  result *= this->one_over_beta;  
  result += this->one_over_tbeta;
  result = 1.0 / result;

  /*
  // short version
  result = (this->one_over_beta * log((double)r_thermistor / (double)this->r_beta)) + this->one_over_tbeta;
  result = 1.0 / result;
  */

  if (use_fahrenheit)
    result = this->KtoF(result);
  else
    result = this->KtoC(result);

  return result;
}



#ifdef DEBUG
void test_thermistor(void) {
  /*
  Some expected Thermistor stats calculated via data from an datasheet
  
  Beta: 3977

  0°C  32554 - 2.47776
  10°C 19872 - 1.99358
  20°C 12488 - 1.53755
  25°C 12488 - 1.33333
  30°C 8059  - 1.14887
  */
  
  Thermistor t = Thermistor(4.0,
                            20000,
                            3977,
                            10000,
                            25);
  
  Serial.println(String("\nTesting Thermistor Class!"));

  Serial.println("-----------------------------------------");
  Serial.println(String("Should be 0DC: ") + t.calc_temp(2.47776));
  Serial.println(String("Should be 10DC: ") + t.calc_temp(1.99358));
  Serial.println(String("Should be 20DC: ") + t.calc_temp(1.53755));
  Serial.println(String("Should be 25DC: ") + t.calc_temp(1.33333));
  Serial.println(String("Should be 30DC: ") + t.calc_temp(1.14887));
  Serial.println(String("Temp at 0.3V: ") + t.calc_temp(0.3));
  Serial.println(String("Temp at 1.1V: ") + t.calc_temp(1.1));
  Serial.println(String("Temp at 2.56V: ") + t.calc_temp(2.56));
  Serial.println(String("Temp at 3V: ") + t.calc_temp(3.0));
  Serial.println(String("Temp at 3.5V: ") + t.calc_temp(3.5));
  Serial.println(String("Temp at 3.8V: ") + t.calc_temp(3.8));
  Serial.println("-----------------------------------------");
}
#endif
